<template>
    <div class="user-login-container">
        <Background></Background>
        <div class="title">Please login</div>
        <div class="form-box">
            <el-form :model="form" status-icon :rules="rules" ref="formRef" size="large">
                <el-form-item prop="account">
                    <el-input
                        placeholder="account or email"
                        prefix-icon="User"
                        v-model="form.account"
                        clearable
                    />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input
                        type="password"
                        placeholder="password"
                        prefix-icon="Lock"
                        v-model="form.password"
                        clearable
                    />
                </el-form-item>
                <el-form-item>
                    <el-button
                        :disabled="loading"
                        type="primary"
                        style="width: 100%"
                        @click="submitForm"
                    >
                        {{ buttonName }}
                    </el-button>
                </el-form-item>
            </el-form>
            <div class="nav">
                <router-link to="/">忘记密码</router-link>
                <router-link to="/">注册</router-link>
            </div>

            <el-page-header content="Back to the blog" @back="goBack" />
        </div>
    </div>
</template>

<script>
import { getCurrentInstance, ref, reactive } from 'vue';
import Background from '@/components/layout/BasicLayoutBackground.vue';
import userService from '@/global/service/userService.js';

export default {
    name: 'Login',
    components: {
        Background
    },
    setup() {
        const { proxy } = getCurrentInstance();

        let loading = ref(false); // 等待loading
        let buttonName = ref('登陆'); // 登陆按钮
        let form = reactive({ account: '', password: '' }); // 表单
        let rules = {
            account: [{ required: true, message: '用户名或邮件不能空', trigger: 'blur' }],
            password: [
                { required: true, message: '密码不能为空', trigger: 'blur' },
                { min: 2, max: 16, message: '长度2到16个字符', trigger: 'change' }
            ]
        };

        // 快捷键登陆
        const handleEvent = (e) => {
            if (e.keyCode == 13) {
                if (loading.value) return proxy.$msg.warning('操作不能太急');
                // 登录
                submitForm();
            }
        };
        // 返回博客
        const goBack = () => {
            proxy.$router.push({ name: 'Home' });
        };
        // 等待倒计时,防止连续点击登陆操作
        const countdown = () => {
            loading.value = true;
            let time = 30;
            buttonName.value = `(${time})秒重新登陆`;

            const interval = window.setInterval(() => {
                time -= 1;
                buttonName.value = `(${time})秒重新登陆`;
                if (time <= 0) {
                    buttonName.value = '登陆';
                    loading.value = false;
                    window.clearInterval(interval);
                }
            }, 1000);
        };
        // 提交表单
        const submitForm = async () => {
            //表单验证
            await proxy.$refs['formRef'].validate((valid) => {
                if (valid) {
                    countdown();
                }
            });

            if (loading.value) {
                const { code, data, msg } = await userService.login({
                    account: form.account,
                    password: form.password
                });

                if (code === 200) {
                    proxy.$storage.setToken(data.token);
                    proxy.$storage.session.set('userinfo', data.userInfo);
                    proxy.$store.commit('updateToken', data.token);
                    proxy.$store.commit('updateUserInfo', data.userInfo);
                    proxy.$msg.success(msg);

                    // 销毁快捷键监听
                    document.removeEventListener('keydown', handleEvent);

                    goBack();
                } else {
                    proxy.$msg.error(msg);
                }
            }
        };

        // 监听快捷键
        document.addEventListener('keydown', handleEvent);

        return {
            loading,
            buttonName,
            form,
            rules,
            goBack,
            submitForm
        };
    }
};
</script>

<style lang="less">
.user-login-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .title {
        font-size: 30px;
        font-weight: bolder;
        margin-bottom: 30px;
    }

    .form-box {
        width: 300px;

        .el-form-item {
            margin-bottom: 10px;
        }

        .nav {
            margin: 20px 0;
        }
    }

    a {
        color: #000;
        margin-right: 20px;

        &:hover {
            color: #409eff;
        }
    }
}
</style>
